const path = require('path');
const opn = require('opn');
const fs = require('fs');

const { paths } = require('../utils');
const mock = require(path.join(paths.roots, 'src/mock'));
const { webpackConfig, webpackDevServerConfig } = require('./lib/config');

let webHost = webpackConfig.devServer.feHost;
let targetHost = webpackConfig.devServer.host;
let port = webpackConfig.devServer.port;
let serverHost = '0.0.0.0';

const isPrd = process.argv.join(' ').indexOf('--mode production') > -1;

let hosts = fs.readFileSync('/private/etc/hosts','utf-8');
if (hosts.indexOf(webHost) === -1){
  console.log('***************************************************\n');
  console.log('请在hosts里添加\n');
  console.log(`${serverHost} ${webHost}\n`);
  console.log('***************************************************\n');
  process.exit();
}

module.exports = function (env, argv){
  process.env.mode = argv.mode;

  return webpackDevServerConfig || {
    entry: ['react'],
    //output: {},
    devServer: {
      historyApiFallback: {
        rewrites: [{
          from: /.*/g,
          to: path.join(paths.roots, 'v5/index.html')
        }]
      },
      contentBase: isPrd ? paths.prdAsset : paths.devAsset,
      host: serverHost,
      hot: false,
      port,
      quiet: true,
      disableHostCheck: true,
      proxy: {
        '/mock': {
          target: `http://${serverHost}:${port}`,
          changeOrigin: true,
          pathRewrite: { '^/mock': '' },
          secure: false
        },
        '**/*.json': {
          target: `http://${targetHost}`,
          changeOrigin: true,
          secure: false,
        },
        ...webpackConfig.devServer.proxy
      },
      before(app, server) {
        mock && mock(app, server);
      },
      after() {
        opn(`http://${webHost}:${port}/v5/`, { app: 'google chrome' });
      }
    }
  };
}